package com.itheima.website.utils;

import java.lang.reflect.Method;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class BeanFactory {
	
	//通过工厂模式加载
	public static Object createBean(String name,String path) throws Exception {
		//System.out.println(name);
		//通过dom4j,创建SaxReader的
		SAXReader reader = new SAXReader();
		//创建xml文件
        Document document = reader.read(path);
        //获取指定name名称的元素对象,//BBB[@name='bbb']
        Element element = (Element) document.selectSingleNode("//bean[@name='" + name + "']");
        //获取类的全名
        String value = element.attributeValue("class");
        return Class.forName(value).newInstance();
	}
	
	//属性注入
	public static Object propertyIntoObject(Object obj,String username,String password) throws Exception {
		//反射获取方法
		Class<? extends Object> clazz = obj.getClass();
		//获取所有方法
		Method[] methods = clazz.getDeclaredMethods();
		//遍历
		for (Method method : methods) {
			//避开jvm检查
			method.setAccessible(true);
			//获取setUsername
			if(method.getName().equalsIgnoreCase("setUsername")) {
				//执行赋值
				method.invoke(obj, username);
			}
			//获取setPassword
			if(method.getName().equalsIgnoreCase("setPassword")) {
				method.invoke(obj, password);
			}
		}
		return obj;
	}

}
